import { TAllTypes, IValue, IValueNumber, IPosition, IAllPosition, IValueString } from '../../types';
import { AFunc, IPositionValue } from '../types';
import { calculate } from '../../calculate';
import { FormulaError } from '../../formula-error';
import { isEqualVal, isEqualCondition } from '../../utils';
export class CountIf extends AFunc {
  public excute(args: TAllTypes[]): TAllTypes[] {
    if(args.length !== 2) {
      throw new FormulaError('#VALUE!', {errorId: '73aa8eed4ede'});
    }
    let dataMatrix: IValue[][] = this.transformToRangeValue(args[0]);
    let count = 0;
    if(args[1].type === 'range' || args[1].type === 'rowPosition' || args[1].type === 'colPosition') {
      return [{type: 'value', dataType: 'number', value: 0}]
      // let conditionMatrix = this.transformToRangeValue(args[1]);
      // for(let i = 0; i < dataMatrix.length; i++) {
      //   if(!Array.isArray(conditionMatrix[i]) || !Array.isArray(dataMatrix[i])) continue;
      //   for(let j = 0; j < dataMatrix[i].length; j++) {
      //     if(conditionMatrix[i][j] ===  undefined) continue;
      //     if(isEqualVal(dataMatrix[i][j], dataMatrix[i][j])) {
      //       count++;
      //     }
      //   }
      // }
    } else {
      let condition = '';
      if(args[1].type === 'position') {
        let tempVal = this.positionVal.getValue(args[1] as IAllPosition)[0];
        if(tempVal.dataType === 'number' || tempVal.dataType === 'string') {
          condition = tempVal.value.toString();
        } else {
          throw new FormulaError('#UNSUPPORT', {errorId: '01dfd87f3a6a'});
        }
      }
      if(args[1].type === 'value') {
        if((args[1] as IValueNumber).dataType === 'number' || (args[1] as IValueString).dataType === 'string') {
          condition = (args[1] as IValueNumber | IValueString).value.toString();
        } else {
          throw new FormulaError('#UNSUPPORT', {errorId: 'a6609109c26a'});
        }
      }
      for(let i = 0; i < dataMatrix.length; i++) {
        if(!Array.isArray(dataMatrix[i])) continue;
        for(let j = 0; j < dataMatrix[i].length; j++) {
          if(isEqualCondition(dataMatrix[i][j], condition)) {
            count++;
          }
        }
      }
    }
    return [{type: 'value', dataType: 'number', value: count}]
  }
}